﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

public partial class mbloginhandler : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["Theme"].ToString(); ;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        security hdds = new security();
        try
        {
            string userid = ""; string compid = "";
            if (Request.QueryString.Count > 0)
            {
                if (getQueryString("req") != "" && getQueryString("req") == "1")
                {
                    RemoveSessions();
                    string sURL = Request.Url.AbsoluteUri.Replace("&req=1", "");
                    string strMeta = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"refresh\" content=\"1;url=" + sURL + "\" /></head><body></body></html>";
                    Response.Write(strMeta);
                    Response.End();
                }
                else
                {
                    userid = getQueryString("uid");
                    compid = getQueryString("cid");
                    if (userid.Trim() == "" || compid.Trim() == "")
                        lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                    else
                    {   //Process login
                        userid = security.decrypt(userid);
                        compid = security.decrypt(compid);
                        HDDatabase HDD = new HDDatabase();
                        if (Session["servercon"] != null)
                            if (Session["servercon"].ToString() != "")
                                HDD = new HDDatabase(Session["servercon"].ToString());
                        DataRow drUsrDetails = HDD.GetTableRow("select * from ngcompanyuser where company_id in (select company_id from ngcompany where af_row_id = '" + compid + "') and af_row_id = '" + userid + "';");
                        if (drUsrDetails != null)
                        {
                            tb_company.Text = drUsrDetails["company_id"].ToString();
                            tb_userid.Text = drUsrDetails["user_id"].ToString();
                            tb_password.Text = security.decrypt(drUsrDetails["password"].ToString());
                            processLogin();
                        }
                        else
                            lblMessage.Text = wrapItAsMessage("<img src=\"Images/info.gif\" alt=\"\"></img>&nbsp;You do not have sufficient access permission.", true);
                        HDD = null;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error in mbloginhandler - Page Load : " + ex.Message);
        }
        finally
        {
        }
    }
    private string getQueryString(string key)
    {
        if (Request.QueryString[key] == null)
            return "";
        return Request.QueryString[key].ToString();
    }
    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }

    #region RemoveSessions
    private void RemoveSessions()  //Added by srivatsan to prevent postback on logout
    {
        deleteCustomLogo();
        security hdds = new security();
        AuditLog AL = new AuditLog();
        AL.updateUserInCompany();
        AL = null;
        if (!Page.User.Identity.IsAuthenticated)
        {
            if (Page.Request.Cookies["ASP.NET_SessionId"] != null)
                Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);

            for (int i = 0; i < Session.Count; i++)
            {
                Session[i] = null;
            }
            LogWriter.WriteLog("Session End : " + DateTime.Now.ToString());
            Session.Abandon();
        }
    }

    private void deleteCustomLogo()
    {
        try
        {
            if (Session["company_afrowid"] != null)
            {
                DirectoryInfo di = new DirectoryInfo(Server.MapPath(".") + "\\Images\\CustomLogo");
                FileInfo[] fis = di.GetFiles(Session["company_afrowid"].ToString() + "*");
                if (fis.Length > 0)
                    File.Delete(fis[0].FullName);
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in deleteCustomLogo: " + e.Message);
        }
    }
    #endregion

    #region Login Process
    private void processLogin()
    {
        AuditLog AL = new AuditLog();
        Session.Remove("dbcon");
        security hds = new security(tb_userid.Text);
        if (!hds.checkLoginAccessDelay()) // Added by 'Imran Gani' on 25-Nov-2013.
        {
            lblMessage.Text = "Login failed. Temporarily access denied.";
            return;
        }
        if (ConfigurationManager.AppSettings["show_company_on_login"] != null) // Added by 'Imran Gani' on 05-May-2014.
            if (ConfigurationManager.AppSettings["show_company_on_login"].Trim() != "")
                if (!Convert.ToBoolean(ConfigurationManager.AppSettings["show_company_on_login"].ToString()))
                {
                    HDDatabase HDD = new HDDatabase(HttpContext.Current.Session["servercon"].ToString());
                    tb_company.Text = HDD.GetColumnValue("select company_id from ngcompanyuser where user_id = '" + tb_userid.Text + "';");
                    HDD = null;
                }
        if (hds.SaaSUserAuthenticate(tb_company.Text, tb_userid.Text, tb_password.Text))
        {
            HDDatabase hddb = new HDDatabase();
            //string strUserFullName = hddb.GetColumnValue("select isnull(first_name,'') + ' ' + isnull(last_name,'') from sy_usr where user_id='" + tb_userid.Text.Replace("'", "''") + "'");
            DataTable dtUsertable = new DataTable(); string strUserFullName = ""; string strUserRole = ""; string strRoleId = ""; string strWelcomeTitle = "";
            dtUsertable = hddb.GetDataTable("select isnull(first_name,'') + ' ' + isnull(last_name,''),af_row_id,locale from sy_usr where user_id='" + tb_userid.Text.Replace("'", "''") + "'");
            if (dtUsertable != null)
                if (dtUsertable.Rows.Count > 0)
                {
                    strUserFullName = HttpUtility.HtmlEncode(dtUsertable.Rows[0][0].ToString());
                    HttpContext.Current.Session["userlocale"] = dtUsertable.Rows[0]["locale"].ToString();
                    DataRow drRole = hddb.GetTableRow("select af_row_id,role_name from sy_rol where af_row_id='" + hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + dtUsertable.Rows[0][1].ToString() + "'") + "'");
                    if (drRole != null)
                    {
                        strRoleId = drRole["af_row_id"].ToString();
                        strUserRole = drRole["role_name"].ToString();
                        //strUserRole = hddb.GetColumnValue("select role_name from sy_rol where af_row_id='" + hddb.GetColumnValue("select role_id from sy_usr_rol where user_id='" + dtUsertable.Rows[0][1].ToString() + "'") + "'");
                    }
                }
            HttpContext.Current.Session["user_name"] = strUserFullName;
            HttpContext.Current.Session["user_role"] = strUserRole;
            HttpContext.Current.Session["userid"] = tb_userid.Text;
            HttpContext.Current.Session["roleid"] = strRoleId;


            string sTheme = "";
            DataTable dtUser = hddb.GetDataTable("select * from sy_usr");
            if (dtUser.Columns.Contains("theme"))
            {
                DataRow[] drr = dtUser.Select("user_id='" + tb_userid.Text.Replace("'", "''").Trim() + "'");
                if (drr.Length > 0)
                {
                    sTheme = drr[0]["theme"].ToString().Trim();
                    Session["user_afrowid"] = dtUser.Columns.Contains("af_row_id") == true ? drr[0]["af_row_id"].ToString() : Session["userid"].ToString();//included by sanal
                    Session["custodian"] = drr[0]["custodian_filter"].ToString();
                    //hds.Insert_AppVariable("current_userafrowid", HttpContext.Current.Session["user_afrowid"].ToString());
                }
            }

            //hds.Insert_AppVariable("current_userid", HttpContext.Current.Session["userid"].ToString());
            //hds.Insert_AppVariable("current_username", HttpContext.Current.Session["user_name"].ToString());

            strWelcomeTitle = CommonFunctions.replaceSystemVariables(hddb.getAcrMemValue("c5016bbf3100ab6f", "WT")); // Added by 'Imran Gani' on 24-Dec-2012, for dynamic welcome title.
            HttpContext.Current.Session["Welcome_Title"] = strWelcomeTitle;

            if (sTheme == "")
                HttpContext.Current.Session["Theme"] = GlobalValues.DefaultTheme;
            else
                HttpContext.Current.Session["theme"] = sTheme;
            AL.logUserInCompany();
            AL.logUserInModel(tb_company.Text, tb_userid.Text, true); // Added by 'Imran Gani' on 25-Nov-2013.
            AL = null;
            //create logo file in server
            createCustomLogo();
            //Response.Redirect("welcome.aspx?id=default");

            // Added by 'Imran Gani' 13-Mar-2013, to get the continue URL of requested page.
            string sUrlContinue = HttpUtility.UrlDecode(Request.QueryString["continue"] != null ? Request.QueryString["continue"].ToString() : "");
            #region Old Message Handling, Commented by 'Imran Gani' on 20-June-2013
            //string[] mesgs = getUserMessages();
            //if (mesgs.Length > 0)
            //{
            //    Response.Clear();
            //    //string mesContent = "<html><head><link href='App_Themes/" + Session["theme"].ToString() + "/" + Session["theme"].ToString().ToLower().Replace("theme", "") + ".css' type='text/css' rel='stylesheet' /></head><body><div style='width:100%;text-align:center;height:100%;border=solid 0px #FF0000;'><div style='width:60%;margin:0 auto;text-align:left;border=solid 1px #EAEAEA;margin-top:50px;'><div class='Grid_Header'>Messages<div><div class='Grid_Header'>$message$<div></div></div></body></html>";
            //    string mesContent = ReadHtmFile("messages.htm");
            //    mesContent = mesContent.Replace("$message$", HttpUtility.HtmlEncode(mesgs[0].Replace("\r\n","</br>")));
            //    mesContent = mesContent.Replace("$theme$", "App_Themes/" + Session["theme"].ToString() + "/" + Session["theme"].ToString().ToLower().Replace("theme", "") + ".css");
            //    mesContent = mesContent.Replace("$continuelink$", sUrlContinue != "" ? sUrlContinue : navigate2Home()); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
            //    Response.Write(mesContent);
            //    Response.End();
            //}
            #endregion
            string msg_id = hddb.GetColumnValue("select af_row_id from sy_messages where active=1 order by modified_at desc;"); // Modified by 'Imran Gani' on 18-Jul-2013, to get recently modified data.
            if (msg_id != "") // Added by 'Imran Gani' on 20-June-2013, to handle message.
                sUrlContinue = "msg.aspx?id=" + msg_id + "&url=" + HttpUtility.UrlEncode((sUrlContinue != "" ? sUrlContinue : navigate2Home()));
            //Response.Redirect("msg.aspx?id=" + msg_id + "&url=" + HttpUtility.UrlEncode((sUrlContinue != "" ? sUrlContinue : navigate2Home())));
            else
                sUrlContinue = (sUrlContinue != "" ? sUrlContinue : navigate2Home()); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
            //Response.Redirect(sUrlContinue != "" ? sUrlContinue : navigate2Home(), false); // Modified by 'Imran Gani' 13-Mar-2013, to redirect a page of necessary URL
            checkPasswordValidityPeriod(sUrlContinue); // Added by 'Imran Gani' on 25-Nov-2013.
        }
        else
        {
            Session["dbcon"] = Session["servercon"];
            AL.logUserInModel(tb_company.Text, tb_userid.Text, false); // Modified by 'Imran Gani' on 25-Nov-2013.
            AL = null;
            hds.HandleLoginAttempts(tb_company.Text, tb_userid.Text, tb_password.Text); // Added by 'Imran Gani' on 25-Nov-2013.
            lblMessage.Text = hds.Message;
        }
    }
    private void createCustomLogo()
    {
        security s = new security();
        string fName = ""; string ext = "";
        if (s.createCustomLogo(ref fName, ref ext))
            Session["hasCustomLogo"] = "1";
        else
            Session["hasCustomLogo"] = "0";
        s = null;
    }
    private string navigate2Home()
    {
        Navigator ng = new Navigator();
        string retrn = ng.getUserHomePage();
        ng = null;
        return retrn;
    }
    /// <summary>
    /// To check Password Validity Period, when user login.
    /// </summary>
    /// <param name="sUrlContinue">URL to continue.</param>
    // Added by 'Imran Gani' on 25-Nov-2013.
    private void checkPasswordValidityPeriod(string sUrlContinue)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dt_pwdSecurityLog = new DataTable();
        string sRecentPwdLogDate;
        try
        {
            string svalidity_period = hdd.GetColumnValue("select mem_value2 from sy_acr_mem where acr_id = '21597547e2b0fa68' and mem_id = 'validity_period' and af_row_id = 'a5cd5d2f7aa7fa0f' and mem_value1 = 'enabled';");
            if (string.IsNullOrEmpty(svalidity_period) || svalidity_period == "0")
                Response.Redirect(sUrlContinue);
            else
            {
                sRecentPwdLogDate = hdd.GetColumnValue("select [created_at] from [sy_password_security_log] where [applies_to] = '" + HttpContext.Current.Session["user_afrowid"].ToString() + "' order by [created_at] desc;");
                if (string.IsNullOrEmpty(sRecentPwdLogDate))
                {
                    AuditLog AL = new AuditLog();
                    AL.WritePasswordSecurityLog(Session["user_afrowid"].ToString(), Session["user_afrowid"].ToString(), security.encrypt(tb_password.Text), "Initiated log");
                    AL = null;
                    Response.Redirect(sUrlContinue);
                }
                else
                {
                    DateTime RecentLogCreatedAt = Convert.ToDateTime(sRecentPwdLogDate);
                    DateTime CurrentDate = DateTime.Now.ToUniversalTime();
                    TimeSpan difference = CurrentDate.Subtract(RecentLogCreatedAt);
                    int TotalDays = Convert.ToInt32(difference.TotalDays);
                    if (TotalDays < Convert.ToInt32(svalidity_period))
                        Response.Redirect(sUrlContinue);
                    else
                    {
                        Response.Redirect("changepassword.aspx?mn=bc98f78ad064743a&pgs_id=335dea653698e7a7&c_url=" + HttpUtility.UrlEncode(sUrlContinue) + "&ViewMode=content");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Default: checkPasswordValidityPeriod: Error: " + ex.Message);
        }
        finally
        {
            dt_pwdSecurityLog.Dispose();
        }
    }
    #endregion
}